<?php

namespace app\admin\controller;

use app\models\{Admin as Model, Region, MoneyLog};
use app\validate\Admin as Validate;
use think\Db;

class Admin extends Base
{

    public function moneylog()
    {
        $model = new MoneyLog();
        $id = $this->request->get('id/d', 0);
        $list = $model->where('user_id', $id)->order('id desc')->paginate(10, false, ['query' => $this->request->param()]);
        return view('', ['list' => $list]);
    }

    public function money_str()
    {
        $id = $this->request->post('id/d', 0);
        $number = $this->request->post('number', 0);
        $number = (float)$number;
        if (empty($id) || empty($number)) {
            return json(['status' => 1, 'msg' => '合伙人ID或更改数量不能为0']);
        }
        $admin =  $this->request->admin;
        if ($admin['type'] != 1) {
            return json(['status' => 1, 'msg' => '非总管理员无权限操作']);
        }
        $otheradmin = (new Model())->where('id', $id)->find();
        if (empty($otheradmin)) {
            return json(['status' => 1, 'msg' => '管理员不存在']);
        }
        if ($number < 0 && abs($number) > $otheradmin['money']) {
            return json(['status' => 1, 'msg' => '扣除金额超过持有金额']);
        }
        Db::startTrans();
        try {
            (new Model())->MoneyEdit($otheradmin['id'], $otheradmin['money'], $number, 1, 0, "管理员操作");
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::write('回调失败：' . $e, 'weichats');
        }
        return json(['code' => 0, 'msg' => '操作成功']);
    }

    public function index()
    {
        $admin =  $this->request->admin;
        $admin['area'] = explode(',', $admin['area']);
        $admin['street'] = explode(',', $admin['street']);
        $data = $this->request->get();
        $results = (new Model())->order('id desc');
        if (!empty($data['title'])) {
            $results = $results->where('nickname|username', 'like', '%' . $data['title'] . '%');
        }
        if ($admin['type'] == 1) {
            $results = $results->paginate();
        } elseif ($admin['type'] == 2) {
            $results = $results->where('id', '<>', $admin['id'])->where(['area' => $admin['area'], 'type' => [3, 4]])->paginate();
        } elseif ($admin['type'] == 3) {
            $results = $results->where('id', '<>', $admin['id'])->where(['street' => $admin['street'], 'type' => 4])->paginate();
        } else {
            $results = [];
        }
        foreach ($results as $result) {
            $result['area'] = explode(',', $result['area']);
            $result['street'] = explode(',', $result['street']);
            $result['province_text'] = (new Region())->where(['area_code' => $result['province'], 'level' => 1])->value('name');
            $result['city_text'] = (new Region())->where(['area_code' => $result['city'], 'level' => 2])->value('name');
            $result['area_text'] = (new Region())->where(['area_code' => $result['area'], 'level' => 3])->select();
            $result['street_text'] = (new Region())->where(['id' => $result['street'], 'level' => 4])->select();
        }
        return view(null, [
            'list' => $results
        ]);
    }

    public function input()
    {
        $admin =  $this->request->admin;
        if ($this->request->isPost()) {
            $data = $this->request->post('data');
            $validate = new Validate([
                'nickname' => 'require|length:5,200',
                'username' => 'require|alphaNum|length:5,100',
                'type' => 'require|in:1,2,3,4',
            ], [
                'nickname.require' => '备注名称不能为空',
                'nickname.length' => '备注长度不能低于5个字符',
                'username.require' => '用户账号不能为空',
                'username.alphaNum' => '用户账号只能是数字或字母',
                'username.length' => '用户账号长度不能低于5个字符',
                'type.require' => '账号类型不能为空',
                'type.in' => '账号类型不正确',
            ]);
            if (!$validate->scene('add')->check($data) && empty($data['id'])) {
                return json(['status' => 1, 'msg' => $validate->getError()]);
            }
            if (!$validate->scene('edit')->check($data) && !empty($data['id'])) {
                return json(['status' => 1, 'msg' => $validate->getError()]);
            }
            $entry = $this->get_rand_str();
            if ($admin['type'] != 1 && $admin['type'] != 2 && $admin['type'] != 3) {
                return json(['status' => 1, 'msg' => '无权限操作']);
            }
            if ($admin['id'] != 1 && $data['type'] == 1) {
                return json(['status' => 1, 'msg' => '非总管理员无法添加超级管理员']);
            }
            if (!empty($data['id']) && $data['id'] == $admin['id']) {
                $data['province'] = $admin['province'];
                $data['city'] = $admin['city'];
                $data['area'] = $admin['area'];
                $data['street'] = $admin['street'];
                $data['type'] = $admin['type'];
            }
            $haveadmin = (new Model())->where('username', $data['username'])->find();
            if (!empty($haveadmin) && $haveadmin['id'] != $data['id']) {
                return json(['status' => 1, 'msg' => '账号名称已被使用']);
            }
            if ($data['type'] == 0 || $data['type'] == 1) {
                $data['area'] = [];
                $data['street'] = [];
            }
            if ($data['type'] == 2) {
                $data['street'] = [];
            }
            if ($data['type'] == 3) {
                if (count($data['area']) != 1) {
                    return json(['status' => 1, 'msg' => '区、县合伙人只能管理一个区域']);
                }
            }
            if ($data['type'] == 4) {
                if (empty($data['area']) || count($data['area']) != 1) {
                    return json(['status' => 1, 'msg' => '区、县合伙人只能管理一个区域']);
                }
                if (empty($data['street']) || count($data['street']) != 1) {
                    return json(['status' => 1, 'msg' => '村、镇合伙人只能管理一个街道']);
                }
            }
            if ($admin['type'] == 2) {
                if ($data['type'] != 3 && $data['type'] != 4) {
                    return json(['status' => 1, 'msg' => '当前级别只能添加区县合伙人']);
                }
                if (empty($data['area']) || empty($data['area'][0])) {
                    return json(['status' => 1, 'msg' => '必须选择管理区域']);
                }
                if (empty($data['street']) || empty($data['street'][0])) {
                    return json(['status' => 1, 'msg' => '必须选择管理街道、村、镇']);
                }
                $admin['area'] = explode(',', $admin['area']);
                if (!in_array($data['area'][0], $admin['area'])) {
                    return json(['status' => 1, 'msg' => '非管理区域，无法添加下级合伙人']);
                }
            }
            if ($admin['type'] == 3) {
                if ($data['type'] <= 3) {
                    return json(['status' => 1, 'msg' => '当前级别只能添加村镇合伙人']);
                }
                if (empty($data['area']) || empty($data['area'][0])) {
                    return json(['status' => 1, 'msg' => '必须选择管理区域']);
                }
                if (empty($data['street']) || empty($data['street'][0])) {
                    return json(['status' => 1, 'msg' => '必须选择管理街道、村、镇']);
                }
                $admin['street'] = explode(',', $admin['street']);
                if (!in_array($data['street'][0], $admin['street'])) {
                    return json(['status' => 1, 'msg' => '非管理区域，无法添加下级合伙人']);
                }
            }
            $data['role'] = implode(',', $data['role']);
            $data['area'] = implode(',', $data['area']);
            $data['street'] = implode(',', $data['street']);
            $entry = $this->get_rand_str();
            if (isset($data['password']) && $data['password']) {
                $data['entry'] = $entry;
                $data['password'] = md5(md5($data['password']) . md5($entry));
            } else {
                unset($data['password']);
            }
            if ($data['id'] > 0) {
                if (!$validate->scene('edit')->check($data)) {
                    return json(['status' => 1, 'msg' => $validate->getError()]);
                }
                $res = (new Model())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new Model())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 0, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $data = (new Model())->where('id', $id)->find();
            if (!empty($data)) {
                $data['role'] = explode(',', $data['role']);
                $data['area'] = explode(',', $data['area']);
                $data['street'] = explode(',', $data['street']);
            } else {
                $data['role'] = [];
            }
            return view('', [
                'data' => $data,
                'role' => $this->request->admin['role'],
                'type' => $this->request->admin['type'],
            ]);
        }
    }

    public function del()
    {
        $admin_id =  $this->request->get('id');
        $admin = (new Model())->where('id', $admin_id)->find();
        if ($admin['is_default'] == 1) {
            return json(['status' => 1, 'msg' => '超级管理员不允许删除']);
        }
        $res = (new Model())->where('id', $admin_id)->delete();
        if ($res) {
            return json(['status' => 0, 'msg' => '删除成功']);
        }
        return json(['status' => 1, 'msg' => '操作失败']);
    }

    //登录日志
    public function login_log()
    {
        $data = input('param.');
        $list = Db::table('tb_admin_login')->where('uid', $this->request->admin['id'])->order('id DESC');
        if (isset($data['username']) && $data['username']) {
            $list->where('username', $data['username']);
        }
        $lists = $list->paginate(10, false, ['query' => $this->request->param()]);

        return view('', ['list' => $lists]);
    }
}
